package com.syaccp.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;;
import com.github.pagehelper.PageInfo;
import com.syaccp.model.*;
import com.syaccp.page.pageUtils;
import com.syaccp.request.TOrderMaterialRequest;
import com.syaccp.response.OrderDetailStatus;
import com.syaccp.response.PicturePath;
import com.syaccp.response.TOrderMaterialResponse;
import com.syaccp.service.TOrderDetailService;
import com.syaccp.service.TOrderService;
import com.syaccp.utils.AliOSSUtils;
import com.syaccp.utils.Result;
import com.syaccp.utils.imgUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Api("操作任务表")
@RestController
@CrossOrigin
@RequestMapping("/api/tOrderDetail/")
public class TOrderDetailController {



    @Resource
    private AliOSSUtils aliOSSUtils;

    @Resource
    TOrderService tOrderService;
    @Resource
    TOrderDetailService tOrderDetailService;

    @ApiOperation(value = "批量删除任务")
    @GetMapping("/delInfoByIds")
    public Result<Integer> delInfoByIds(@RequestParam List<Integer> ids){
        return Result.success(tOrderDetailService.delInfoByIds(ids));
    }
    @ApiOperation(value = "批量设为精选")
    @GetMapping("/updateSelections")
    public Result<Integer> updateSelections(@RequestParam List<Integer> ids){
        return Result.success(tOrderDetailService.updateSelection(ids));
    }

    /**
     * 多条件查询任务
     *
     * @return
     */
    @ApiOperation(value = "操作多条件查询订单表")
    @GetMapping("/queryInfoByManyCondition")
    public synchronized  Result<TOrderMaterialResponse> queryInfoByManyCondition(Integer number, @ModelAttribute TOrderMaterialRequest orderRequest) {
        TOrderMaterialResponse tOrderMaterialResponse = new TOrderMaterialResponse();
        Integer totalCount = tOrderDetailService.queryInfoByConditionsNumber(orderRequest);//查询总条数
        pageUtils page = new pageUtils();
        page.setPageSize(10);
        page.setTotalCount(totalCount);
        if (totalCount > 0) {
            if (number >= page.getTotalPageCount()) {
                page.setCurrPageNo(page.getTotalPageCount());
            } else if (number <= 0) {
                page.setCurrPageNo(1);
            } else {
                page.setCurrPageNo(number);
            }
            tOrderMaterialResponse.setAboutPageInfo(page);  //返回的分页信息
            List<TOrderDetail> tOrderDetailList = tOrderDetailService.queryInfoByConditions(orderRequest, page);//查询并分页
            List<TOrder> aboutOrderInfo=new ArrayList<>();  //相关订单集合
            List<TOrderDetail> detailListCollectTwo = tOrderDetailList.stream().peek(info -> {
                    //通过客户评价和风格特征查询订单
                        aboutOrderInfo.add(tOrderService.queryByOrderId(info.getOrderId()));
                        if (StringUtils.isBlank(info.getImage())) { //拼接图片前缀
                            info.setImage(imgUtils.DEFAULT_PIC);
                        } else {
                            info.setImage(imgUtils.setRealPicPath(info.getImage()));
                            if (!imgUtils.checkUrlConnection(info.getImage())) {
                                info.setImage(imgUtils.DEFAULT_PIC);
                            }
                        }
            }).collect(Collectors.toList());
            tOrderMaterialResponse.setTOrderDetailList(detailListCollectTwo);
            tOrderMaterialResponse.setAboutOrderDetailStyles(aboutOrderInfo);
        }
        return Result.success(tOrderMaterialResponse);
    }

    @ApiOperation(value = "查询审核级别")
    @GetMapping("/queryAllAboutOrderInfo")
    public Result<List<TOrderDetail>> queryAllAboutOrderInfo() {
        return Result.success(tOrderDetailService.queryAuditions());
    }
    @ApiOperation(value = "查询所属公司")
    @GetMapping("/queryAllAboutCompany")
    public Result<List<TOrderDetail>> queryAllAboutCompany() {
        return Result.success(tOrderDetailService.queryCompanyNames());
    }
    @ApiOperation(value = "查询模型师")
    @GetMapping("/queryAllAboutModel")
    public Result<List<TOrderDetail>> queryAllAboutModel() {
        return Result.success(tOrderDetailService.queryModelNames());
    }






    @ApiOperation(value = "查询附件等级信息")
    @ApiImplicitParam()
    @GetMapping("/QueryModelLevel")
    public Result  QueryModelLevel(){
        List<Dict> dicts = tOrderDetailService.QueryModelLevel();

        return Result.success(dicts);
    }


    @ApiOperation(value = "查询任务图片信息")
    @ApiImplicitParam()
    @GetMapping("/QueryDetailPicture")
    public Result QueryAllDetailMsg(Integer id){
        //查询主图


        //查询赠图

        return Result.success(1);
    }


    @ApiOperation(value = "查询场景类型信息")
    @ApiImplicitParam()
    @GetMapping("/QueryStyleType")
    public Result  QueryStyleType(){
        List<Dict> dicts = tOrderDetailService.QueryStyleType();
        return Result.success(dicts);

    }



    @ApiOperation(value = "查询场景类型信息")
    @ApiImplicitParam()
    @GetMapping("/QuerySceneType")
    public Result QuerySceneType(Integer id){
        System.out.println("1 = " + 1);
        List<TOrderCategory> orderCategories =tOrderDetailService.QuerySceneTypeById(id);
        for (TOrderCategory category : orderCategories) {
            System.out.println("category = " + category);
        }

        return Result.success(orderCategories);

    }

    @ApiOperation(value = "查询附件类型信息")
    @ApiImplicitParam()
    @GetMapping("/QueryAttachmentType")
    public Result QueryAttachmentMsg(Dict dict){
        List<Dict> dicts = tOrderDetailService.QueryAttachmentType(dict);

        return Result.success(dicts);

    }


    @ApiOperation(value = "查询任务状态信息")
    @ApiImplicitParam()
    @GetMapping("/QueryDetailsStatus")
    public Result QueryDetailStatus() {
        Result result = new Result();
        OrderDetailStatus orderDetailStatus = tOrderDetailService.QueryDetailsStatus();
        if (orderDetailStatus != null) {
            result.setCode(200);
            result.setData(orderDetailStatus);
            System.out.println(orderDetailStatus);
            return result;
        } else {
            result.setCode(500);
        }
        return result;

    }



    @ApiOperation(value = "查询公司状态信息")
    @ApiImplicitParam()
    @GetMapping("/QueryCompanyMsg")
    public Result QueryCompanyMsg() {
        Result result = new Result<>();
        List<SysDept> sysDepts = tOrderDetailService.QueryCompanyMsg();
        if (sysDepts != null) {
            result.setCode(200);
            result.setData(sysDepts);
            return result;
        } else {
            result.setCode(500);
        }

        return result;
    }
    @ApiOperation(value = "分页查询所有任务信息")
    @ApiImplicitParam()
    @GetMapping("/QueryAllDetail")
    public Result QueryAllDetailMsg(TOrderDetail orderDetail){
        Result result=new Result();
        System.out.println(orderDetail);
        PageInfo<TOrderDetail> orderDetailPageInfo = tOrderDetailService.QueryAllDetail(orderDetail, orderDetail.getIndex());
        List<TOrderDetail> list = orderDetailPageInfo.getList();

        if (orderDetailPageInfo!=null){
            //查询成功
            result.setCode(200);
            for (TOrderDetail detail : list) {

                if (detail.getQuanjiUrl()!=null){
                    //设置主图片路径
                    String picture_get_path = PicturePath.GET_PICTURE_GET_PATH(detail.getImage());
                    detail.setImage(picture_get_path);
                    System.out.println(detail.getImage());
                }
                else if (detail.getQuanjiUrl()==null){
                    //oss路径
                    if (detail.getImage()!=null){
                        if(detail.getImage().contains("oss")==true){
                            String picture_get_path = PicturePath.GET_PICTURE_GET_PATH(detail.getImage());
                            detail.setImage(picture_get_path);
                        }else {
                            detail.setImage(null);
                        }
                    }
                }

                //设置赠图路径
                if (detail.getAlbumPics()!=null){
                    List list1 = PicturePath.GET_ALBUM_PICS(detail.getAlbumPics());
                    detail.setAlbumList(list1);
                }
                //设置付款进程
                if (detail.getMoney()!=0){
                    //付款进程
                    Double money= Double.valueOf(detail.getMoney());
                    Double paidMoney= Double.valueOf(detail.getPaidMoney());
                    int course = (int) ((paidMoney/money) * 100);
                    //付款余数
                    int BalanceOfPayment = detail.getMoney() - detail.getPaidMoney();
                    detail.setCourse(course);
                    detail.setBalanceOfPayment(BalanceOfPayment);
                }else if (detail.getMoney()==0&&detail.getStatus()==1){
                    detail.setCourse(-1);
                    detail.setBalanceOfPayment(-1);
                }else if (detail.getMoney()==0&&detail.getStatus()==4){
                    detail.setCourse(-2);
                    detail.setBalanceOfPayment(-2);
                }else if (detail.getMoney()==0&&detail.getStatus()==5){
                    detail.setCourse(100);
                    detail.setBalanceOfPayment(0);
                }
            }

            result.setData(orderDetailPageInfo);
            return  result;

        }else {
            //查询失败
            result.setCode(500);
        }
        return result;
    }

    @ApiOperation(value = "根据任务id查询任务编号")
    @ApiImplicitParam()
    @GetMapping("/QueryOrderNameById")
    public Result QueryOrderNameByIdMsg(Integer id){
        Result result=new Result();
        TOrder order = tOrderDetailService.QueryOrderNameById(id);
        if (order != null) {
            result.setCode(200);
            result.setData(order);
            return result;
        } else {
            result.setCode(500);
        }
        return result;
    }

    @PutMapping(value = "IsDelete/{id}")
    @ApiOperation(value = "逻辑删除",notes = "逻辑删除任务信息")
    @ApiImplicitParam(name = "id", value = "任务id")
    public Result IsDeleteTask(@PathVariable Integer id){
        System.out.println("id = " + id);
        Integer integer = tOrderDetailService.IsDelete(id);
        return Result.success(integer);
    }


    @PostMapping(value = "/upAttachment")
    @ApiOperation(value = "上传附件",notes = "上传附件信息")
    public Result upAttachment(
            @RequestParam (value = "files" ,required = false) MultipartFile[] file,
            @RequestParam("modelLightName")String modelLightName ,
            @RequestParam("modelLightId")Integer modelLightId,
            @RequestParam("modelCzName") String modelCzName,
            @RequestParam("modelCzId") Integer modelCzId,
            @RequestParam("modelMaxId")Integer modelMaxId,
            @RequestParam("modelMaxName") String modelMaxName,
            @RequestParam("taskId") Integer taskId
    ) throws IOException {
        TOrderDetail orderDetail = new TOrderDetail();
        orderDetail.setMakeId(modelMaxId);
        orderDetail.setModelMaxName(modelMaxName);
        orderDetail.setModelLightId(modelLightId);
        orderDetail.setModelLightName(modelLightName);
        orderDetail.setModelCzId(modelCzId);
        orderDetail.setModelCzName(modelCzName);

        DecimalFormat decimalFormat = new DecimalFormat();
        int MB = 1024 * 1024;
        for (int i = 0; i < file.length; i++) {
            String format = decimalFormat.format((file[i].getSize()/(float)MB) )+ "MB";
            orderDetail.setModelSize(format);
            String upload = aliOSSUtils.upload(file[i]);
            orderDetail.setModelFile(upload);
        }



        Date date = new Date();
        String modelNo = String.format("%tH%tM%tS", date, date, date);
        orderDetail.setModelNo(modelNo);


        if (tOrderDetailService.selectOneById(taskId)!=null){
            Integer id = taskId;
            Integer integer = tOrderDetailService.updateOrderDetail(orderDetail ,id);
            return Result.success(integer);
        }else {
            Integer integer = tOrderDetailService.addOrderDetail(orderDetail);
            return Result.success(integer);
        }


    }













}
